<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="综合查询">
          <el-input v-model.trim="queryForm.keywords" style="width: 180px;" clearable placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" border stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="mid" label="模块ID" min-width="180" show-overflow-tooltip />
        <el-table-column prop="name" label="模块名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="isCache" label="是否缓存" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isCache == 1 ? 'success' : 'danger'">
              {{ scope.row.isCache == 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isChoice" label="是否多选" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isChoice == 1 ? 'success' : 'danger'">
              {{ scope.row.isChoice == 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="opWidth" label="操作栏宽度" min-width="100" />
        <el-table-column prop="formWidth" label="表单宽度" min-width="100" />
        <el-table-column prop="roles" label="角色权限" min-width="160" show-overflow-tooltip>
          <template #default="scope">
            {{ formatRoles(scope.row.roles) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ $formatTimestamp(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="height: 18px;"></div>

      <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 50, 100, 500, 1000]" :total="total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 模块表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" fullscreen :close-on-click-modal="false"
      :close-on-press-escape="false" destroy-on-close>
      <el-form ref="formRef" :model="moduleForm" :rules="moduleRules" label-position="top" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="模块ID" prop="mid">
              <el-input v-model.trim="moduleForm.mid" placeholder="模块ID" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="模块名称" prop="name">
              <el-input v-model.trim="moduleForm.name" placeholder="模块名称" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="是否缓存" prop="isCache">
              <el-select v-model="moduleForm.isCache" placeholder="是否缓存">
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="是否多选" prop="isChoice">
              <el-select v-model="moduleForm.isChoice" placeholder="是否多选">
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="操作栏宽度" prop="opWidth">
              <el-input v-model.trim="moduleForm.opWidth" placeholder="操作栏宽度" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="表单宽度" prop="formWidth">
              <el-input v-model.trim="moduleForm.formWidth" placeholder="表单宽度" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="表单标签位置" prop="formLabelPosition">
              <el-select v-model="moduleForm.formLabelPosition" placeholder="表单标签位置">
                <el-option label="居左" value="left" />
                <el-option label="居右" value="right" />
                <el-option label="顶部" value="top" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="表单标签宽度" prop="formLabelWidth">
              <el-input v-model.trim="moduleForm.formLabelWidth" placeholder="表单标签宽度" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="角色权限" prop="roles">
              <el-select v-model="moduleForm.roles" multiple collapse-tags placeholder="请选择角色" style="width: 100%;">
                <el-option v-for="item in roleList" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="字段管理" prop="tableJson">
              <el-table ref="sortableTableRef" :data="tableJson" border row-key="name" style="width: 100%">
                <el-table-column prop="name" label="字段名称" width="200" fixed="left">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.name" placeholder="字段名称" />
                  </template>
                </el-table-column>
                <el-table-column prop="type" label="字段类型" width="180">
                  <template #default="scope">
                    <el-select v-model="scope.row.type" placeholder="字段类型">
                      <el-option label="字符串" value="string" />
                      <el-option label="整数" value="int" />
                      <el-option label="数字" value="number" />
                      <el-option label="字典" value="dict" />
                      <el-option label="字典列表" value="dicts" />
                      <el-option label="图片" value="image" />
                      <el-option label="图片列表" value="images" />
                      <el-option label="文件" value="file" />
                      <el-option label="文件列表" value="files" />
                      <el-option label="文本" value="text" />
                      <el-option label="富文本" value="richtext" />
                      <el-option label="对象" value="object" />
                      <el-option label="对象列表" value="objects" />
                      <el-option label="树形数据" value="tree" />
                      <el-option label="日期" value="date" />
                      <el-option label="时间戳" value="timestamp" />
                      <el-option label="JSON" value="json" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="字段描述" width="200">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.remark" placeholder="字段描述" />
                  </template>
                </el-table-column>
                <el-table-column prop="defaultValue" label="默认值" width="160">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.defaultValue" placeholder="默认值" />
                  </template>
                </el-table-column>
                <el-table-column prop="associateObject" label="关联对象" width="160">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.associateObject" placeholder="关联对象" />
                  </template>
                </el-table-column>
                <el-table-column prop="showTable" label="表格显示" width="90">
                  <template #default="scope">
                    <el-switch v-model="scope.row.showTable" />
                  </template>
                </el-table-column>
                <el-table-column prop="isAdd" label="是否新增" width="90">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isAdd" />
                  </template>
                </el-table-column>
                <el-table-column prop="isEdit" label="是否编辑" width="90">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isEdit" />
                  </template>
                </el-table-column>
                <el-table-column prop="isBatchEdit" label="批量编辑" width="90">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isBatchEdit" />
                  </template>
                </el-table-column>
                <el-table-column prop="isRequired" label="是否必填" width="90">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isRequired" />
                  </template>
                </el-table-column>
                <el-table-column prop="isQuery" label="关键字查询" width="100">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isQuery" />
                  </template>
                </el-table-column>
                <el-table-column prop="isSingleQuery" label="单独查询" width="90">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isSingleQuery" />
                  </template>
                </el-table-column>
                <el-table-column prop="isSort" label="是否排序" width="90">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isSort" />
                  </template>
                </el-table-column>
                <el-table-column prop="isUnique" label="唯一校验" width="90">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isUnique" />
                  </template>
                </el-table-column>
                <el-table-column prop="isLock" label="列锁定" width="90">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isLock" />
                  </template>
                </el-table-column>
                <el-table-column prop="columnWidth" label="固定列宽度" width="160">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.columnWidth" placeholder="固定列宽度" />
                  </template>
                </el-table-column>
                <el-table-column prop="minColumnWidth" label="最小列宽度" width="160">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.minColumnWidth" placeholder="最小列宽度" />
                  </template>
                </el-table-column>
                <el-table-column prop="rowLayout" label="行布局" width="180">
                  <template #default="scope">
                    <el-input-number v-model="scope.row.rowLayout" :step="4" :min="4" :max="24" />
                  </template>
                </el-table-column>
                <el-table-column prop="dictFunc" label="字典选择后执行方法" width="200">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.dictFunc" placeholder="字典选择后执行方法">
                      <template #suffix>
                        <el-icon class="pointer">
                          <edit />
                        </el-icon>
                      </template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="roles" label="角色权限" min-width="500">
                  <template #default="scope">
                    <el-checkbox-group v-model="scope.row.roles">
                      <el-checkbox v-for="item in roleList" :label="item.name" :value="item.code" />
                    </el-checkbox-group>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="130" fixed="right">
                  <template #default="scope">
                    <el-button size="small" :icon="Rank" circle class="btn-drag"></el-button>
                    <el-button size="small" type="primary" :icon="Plus" circle
                      @click="tableJson.splice(scope.$index, 0, { name: '', type: 'string', remark: '', defaultValue: '', associateObject: '', showTable: false, isAdd: false, isEdit: false, isBatchEdit: false, isRequired: false, isQuery: false, isSingleQuery: false, isSort: false, isUnique: false, isLock: false, columnWidth: '', minColumnWidth: '', rowLayout: 12, dictFunc: '', roles: [] })"></el-button>
                    <el-button size="small" type="danger" :icon="Delete" circle
                      @click="tableJson.splice(scope.$index, 1)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 10px;">
                <el-button type="primary" size="small"
                  @click="tableJson.push({ name: '', type: 'string', remark: '', defaultValue: '', associateObject: '', showTable: false, isAdd: false, isEdit: false, isBatchEdit: false, isRequired: false, isQuery: false, isSingleQuery: false, isSort: false, isUnique: false, isLock: false, columnWidth: '', minColumnWidth: '', rowLayout: 12, dictFunc: '', roles: [] })">添加字段</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="按钮管理" prop="btnJson">
              <el-table ref="sortableBtnRef" :data="btnJson" border row-key="name" style="width: 100%">
                <el-table-column prop="name" label="按钮名称" width="200" fixed="left">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.name" placeholder="按钮名称" />
                  </template>
                </el-table-column>
                <el-table-column prop="position" label="按钮位置" width="180">
                  <template #default="scope">
                    <el-select v-model="scope.row.position" placeholder="按钮位置">
                      <el-option label="搜索栏" value="searchBar" />
                      <el-option label="操作栏" value="actionBar" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="color" label="按钮颜色" width="100">
                  <template #default="scope">
                    <el-color-picker v-model.trim="scope.row.color" />
                  </template>
                </el-table-column>
                <el-table-column prop="func" label="执行方法" width="200">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.btnFunc" placeholder="执行方法">
                      <template #suffix>
                        <el-icon class="pointer">
                          <edit />
                        </el-icon>
                      </template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="showCondition" label="根据条件显示" width="200">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.showCondition" placeholder="显示条件">
                      <template #suffix>
                        <el-icon class="pointer">
                          <edit />
                        </el-icon>
                      </template>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="roles" label="角色权限" min-width="500">
                  <template #default="scope">
                    <el-checkbox-group v-model="scope.row.roles">
                      <el-checkbox v-for="item in roleList" :label="item.name" :value="item.code" />
                    </el-checkbox-group>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                  <template #default="scope">
                    <el-button size="small" :icon="Rank" circle class="btn-drag"></el-button>
                    <el-button size="small" type="danger" :icon="Delete" circle
                      @click="btnJson.splice(scope.$index, 1)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 10px;">
                <el-button type="primary" size="small"
                  @click="btnJson.push({ position: '', name: '', color: '', btnFunc: '', showCondition: '', roles: [] })">添加按钮</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="接口管理" prop="apiJson">
              <el-table ref="sortableApiRef" :data="apiJson" border row-key="name" style="width: 100%">
                <el-table-column prop="name" label="接口名称" width="200">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.name" placeholder="接口名称" />
                  </template>
                </el-table-column>
                <el-table-column prop="url" label="接口URL" width="300">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.url" placeholder="接口URL" />
                  </template>
                </el-table-column>
                <el-table-column prop="roles" label="角色权限" min-width="500">
                  <template #default="scope">
                    <el-checkbox-group v-model="scope.row.roles">
                      <el-checkbox v-for="item in roleList" :label="item.name" :value="item.code" />
                    </el-checkbox-group>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                  <template #default="scope">
                    <el-button size="small" :icon="Rank" circle class="btn-drag"></el-button>
                    <el-button size="small" type="danger" :icon="Delete" circle
                      @click="apiJson.splice(scope.$index, 1)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 10px;">
                <el-button type="primary" size="small"
                  @click="apiJson.push({ name: '', url: '', roles: [] })">添加接口</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Rank, Delete, Plus, Edit } from '@element-plus/icons-vue'
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Sortable from 'sortablejs'
import { apiModuleList, apiModuleAdd, apiModuleUpdate, apiModuleDelete } from '@/api/system/module'
import { apiRoleCacheList } from '@/api/system/role'

// 字段管理
const tableJson = ref<Record<string, any>>([])
const initTableJson = ref<Record<string, any>>([
  { name: 'id', type: 'int', remark: 'ID', defaultValue: '', associateObject: '', showTable: true, isAdd: false, isEdit: false, isBatchEdit: false, isRequired: false, isQuery: false, isSingleQuery: false, isSort: false, isUnique: false, isLock: false, columnWidth: 80, minColumnWidth: '', rowLayout: 12, dictFunc: '', roles: [] },
  { name: '', type: 'string', remark: '', defaultValue: '', associateObject: '', showTable: false, isAdd: false, isEdit: false, isBatchEdit: false, isRequired: false, isQuery: false, isSingleQuery: false, isSort: false, isUnique: false, isLock: false, columnWidth: '', minColumnWidth: '', rowLayout: 12, dictFunc: '', roles: [] },
  { name: 'create_by', type: 'int', remark: '创建人', defaultValue: '', associateObject: '', showTable: false, isAdd: false, isEdit: false, isBatchEdit: false, isRequired: false, isQuery: false, isSingleQuery: false, isSort: false, isUnique: false, isLock: false, columnWidth: '', minColumnWidth: '', rowLayout: 12, dictFunc: '', roles: [] },
  { name: 'create_time', type: 'int', remark: '创建时间', defaultValue: '', associateObject: '', showTable: false, isAdd: false, isEdit: false, isBatchEdit: false, isRequired: false, isQuery: false, isSingleQuery: false, isSort: false, isUnique: false, isLock: false, columnWidth: '180', minColumnWidth: '', rowLayout: 12, dictFunc: '', roles: [] },
  { name: 'update_by', type: 'int', remark: '更新人', defaultValue: '', associateObject: '', showTable: false, isAdd: false, isEdit: false, isBatchEdit: false, isRequired: false, isQuery: false, isSingleQuery: false, isSort: false, isUnique: false, isLock: false, columnWidth: '', minColumnWidth: '', rowLayout: 12, dictFunc: '', roles: [] },
  { name: 'update_time', type: 'int', remark: '更新时间', defaultValue: '', associateObject: '', showTable: true, isAdd: false, isEdit: false, isBatchEdit: false, isRequired: false, isQuery: false, isSingleQuery: false, isSort: false, isUnique: false, isLock: false, columnWidth: '180', minColumnWidth: '', rowLayout: 12, dictFunc: '', roles: [] },
  { name: 'is_deleted', type: 'int', remark: '逻辑删除', defaultValue: '0', associateObject: '', showTable: false, isAdd: false, isEdit: false, isBatchEdit: false, isRequired: false, isQuery: false, isSingleQuery: false, isSort: false, isUnique: false, isLock: false, columnWidth: '', minColumnWidth: '', rowLayout: 12, dictFunc: '', roles: [] },
])
// 按钮管理
const btnJson = ref<Record<string, any>>([])
const initBtnJson = ref<Record<string, any>>([
  { name: '查询', position: 'searchBar', color: '#1e8cfe', btnFunc: 'handleQuery', showCondition: '', roles: ["admin"] },
  { name: '新增', position: 'searchBar', color: '#1e8cfe', btnFunc: 'handleAdd', showCondition: '', roles: ["admin"] },
  { name: '批量修改', position: 'searchBar', color: '#1e8cfe', btnFunc: 'handleBatchEdit', showCondition: '', roles: ["admin"] },
  { name: '批量删除', position: 'searchBar', color: '#f62f2f', btnFunc: 'handleBatchDelete', showCondition: '', roles: ["admin"] },
  { name: '编辑', position: 'actionBar', color: '#1e8cfe', btnFunc: 'handleEdit', showCondition: '', roles: ["admin"] },
  { name: '删除', position: 'actionBar', color: '#f62f2f', btnFunc: 'handleDelete', showCondition: '', roles: ["admin"] }
])
// 接口管理
const apiJson = ref<Record<string, any>>([])
const initApiJson = ref<Record<string, any>>([
  { name: '查询', url: '/core/list', roles: ["admin"] },
  { name: '新增', url: '/core/add', roles: ["admin"] },
  { name: '修改', url: '/core/update', roles: ["admin"] },
  { name: '批量修改', url: '/core/batchUpdate', roles: ["admin"] },
  { name: '删除', url: '/core/delete', roles: ["admin"] }
])

// 查询表单
const queryForm = ref<Record<string, any>>({
  pageNum: 1,
  pageSize: 10
})

// 列表与分页
const list = ref<any[]>([])
const roleList = ref<any[]>([])
const total = ref(0)

// 获取列表
const fetchList = async () => {
  const res = await apiModuleList(queryForm.value)
  list.value = res.data?.records || []
  total.value = res.data?.totalRow || 0
}

// 角色列表
const initRoleList = async () => {
  const res = await apiRoleCacheList()
  roleList.value = res.data || []
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 模块表单
const initModuleForm = ref<Record<string, any>>({
  isCache: 0,
  isChoice: 0,
  opWidth: '160',
  formWidth: '600',
  formLabelPosition: 'right',
  formLabelWidth: '100',
  tableJson: [],
  btnJson: [],
  apiJson: []
})
const moduleForm = ref<Record<string, any>>({ ...initModuleForm.value })

// 表单验证规则
const moduleRules = {
  mid: [{ required: true, message: '请输入模块ID', trigger: 'blur' }],
  name: [{ required: true, message: '请输入模块名称', trigger: 'blur' }],
  isCache: [{ required: true, message: '请选择是否缓存', trigger: 'blur' }],
  isChoice: [{ required: true, message: '请选择是否多选', trigger: 'blur' }],
  opWidth: [{ required: true, message: '请输入操作栏宽度', trigger: 'blur' }],
  formWidth: [{ required: true, message: '请输入表单宽度', trigger: 'blur' }],
  formLabelPosition: [{ required: true, message: '请选择表单标签位置', trigger: 'blur' }],
  formLabelWidth: [{ required: true, message: '请输入表单标签宽度', trigger: 'blur' }],
}

// 表单引用
const formRef = ref()

// 查询
const handleQuery = () => {
  queryForm.value.pageNum = 1
  fetchList()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增模块'
  isEdit.value = false
  // 重置表单
  Object.assign(tableJson.value = [], initTableJson.value)
  Object.assign(btnJson.value = [], initBtnJson.value)
  Object.assign(apiJson.value = [], initApiJson.value)
  Object.assign(moduleForm.value = {}, initModuleForm.value)
  dialogVisible.value = true
  nextTick(() => {
    initBtnRowSortable()
    initApiRowSortable()
    initTableRowSortable()
  })
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑模块'
  isEdit.value = true
  // 填充表单数据
  tableJson.value = JSON.parse(row.tableJson) || []
  btnJson.value = JSON.parse(row.btnJson) || []
  apiJson.value = JSON.parse(row.apiJson) || []
  Object.assign(moduleForm.value, row)
  if (moduleForm.value.roles) {
    moduleForm.value.roles = moduleForm.value.roles.split(',')
  }
  dialogVisible.value = true
  nextTick(() => {
    initBtnRowSortable()
    initApiRowSortable()
    initTableRowSortable()
  })
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await apiModuleDelete({ ids: String(row.id) })
    if (res.code == 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      let res: any;
      moduleForm.value.tableJson = JSON.stringify(tableJson.value)
      moduleForm.value.btnJson = JSON.stringify(btnJson.value)
      moduleForm.value.apiJson = JSON.stringify(apiJson.value)
      if (moduleForm.value.roles) {
        //将角色列表转换为逗号分隔的字符串
        moduleForm.value.roles = moduleForm.value.roles.join(',')
      }
      if (isEdit.value) {
        res = await apiModuleUpdate(moduleForm.value)
      } else {
        res = await apiModuleAdd(moduleForm.value)
      }
      if (res.code == 200) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        handleQuery()
      } else {
        ElMessage.error(res.message || '保存失败')
      }
    }
  })
}

// 分页相关
const handleSizeChange = (val: number) => {
  queryForm.value.pageSize = val
  queryForm.value.pageNum = 1
  fetchList()
}

const handleCurrentChange = (val: number) => {
  queryForm.value.pageNum = val
  fetchList()
}

// 表格拖动排序
const sortableApiRef = ref()
let rowApiSortableInstance: any = null
const sortableBtnRef = ref()
let rowBtnSortableInstance: any = null
const sortableTableRef = ref()
let rowTableSortableInstance: any = null

// 初始化行拖拽
const initApiRowSortable = () => {
  if (!sortableApiRef.value) return
  const tbody = sortableApiRef.value.$el.querySelector('.el-table__body-wrapper tbody')
  if (tbody) {
    if (rowApiSortableInstance) {
      rowApiSortableInstance.destroy()
    }
    rowApiSortableInstance = Sortable.create(tbody, {
      animation: 150,
      handle: '.btn-drag',
      ghostClass: 'row-ghost',
      chosenClass: 'row-chosen',
      dragClass: 'row-drag',
      onEnd: handleApiRowDragEnd,
    })
  }
}
const initBtnRowSortable = () => {
  if (!sortableBtnRef.value) return
  const tbody = sortableBtnRef.value.$el.querySelector('.el-table__body-wrapper tbody')
  if (tbody) {
    if (rowBtnSortableInstance) {
      rowBtnSortableInstance.destroy()
    }
    rowBtnSortableInstance = Sortable.create(tbody, {
      animation: 150,
      handle: '.btn-drag',
      ghostClass: 'row-ghost',
      chosenClass: 'row-chosen',
      dragClass: 'row-drag',
      onEnd: handleBtnRowDragEnd,
    })
  }
}
const initTableRowSortable = () => {
  if (!sortableTableRef.value) return
  const tbody = sortableTableRef.value.$el.querySelector('.el-table__body-wrapper tbody')
  if (tbody) {
    if (rowTableSortableInstance) {
      rowTableSortableInstance.destroy()
    }
    rowTableSortableInstance = Sortable.create(tbody, {
      animation: 150,
      handle: '.btn-drag',
      ghostClass: 'row-ghost',
      chosenClass: 'row-chosen',
      dragClass: 'row-drag',
      onEnd: handleTableRowDragEnd,
    })
  }
}

// 行拖拽结束
const handleApiRowDragEnd = (evt: any) => {
  const { oldIndex, newIndex } = evt
  if (oldIndex != newIndex) {
    const movedItem = apiJson.value.splice(oldIndex, 1)[0]
    apiJson.value.splice(newIndex, 0, movedItem)
  }
}
const handleBtnRowDragEnd = (evt: any) => {
  const { oldIndex, newIndex } = evt
  if (oldIndex != newIndex) {
    const movedItem = btnJson.value.splice(oldIndex, 1)[0]
    btnJson.value.splice(newIndex, 0, movedItem)
  }
}
const handleTableRowDragEnd = (evt: any) => {
  const { oldIndex, newIndex } = evt
  if (oldIndex != newIndex) {
    const movedItem = tableJson.value.splice(oldIndex, 1)[0]
    tableJson.value.splice(newIndex, 0, movedItem)
  }
}

// 格式化角色列表
const formatRoles = (roles: string) => {
  if (!roles) return '--'
  return roles.split(',').map(code =>
    roleList.value.find(role => role.code === code)?.name || code
  ).join(',')
}

// 初始化
onMounted(() => {
  fetchList()
  initRoleList()
})
</script>

<style scoped>
.app-container {
  padding: 0px;
}

.query-form {
  margin-bottom: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  position: fixed;
  bottom: 0;
  background-color: #ffffff;
  width: 97%;
  z-index: 100;
  text-align: center;
  padding: 10px 0;
}

.dark .dialog-footer {
  background-color: #141414;
}
</style>